package cn.rjzjh.tapestry.component.services.impl;

import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.PersistentLocale;

import cn.rjzjh.commons.util.apiext.StringUtil;
import cn.rjzjh.tapestry.component.services.ISupportedLocales;

public class SupportedLocalesImpl implements ISupportedLocales {
	private String supportedLocales;
	@Inject
	private PersistentLocale persistentLocale;

	@Inject
	@Symbol(SymbolConstants.CONTEXT_PATH)
	private String contextPath;

	public SupportedLocalesImpl(
			@Inject @Symbol("tapestry.supported-locales") String locales) {
		supportedLocales = locales;
	}

	public String getSupportedLocales() {
		return supportedLocales;
	}

	public void setLocale(String lang) {
		Locale local = new Locale(lang);
		persistentLocale.set(local);
	}

	public Locale getCurLocale() {
		if (persistentLocale.get() == null) {// 默认设置为中文
			persistentLocale.set(Locale.CHINESE);
		}
		return persistentLocale.get();
	}

	/****
	 * 构建国际化的URL，如果带有contextPath表示是绝对路径，无需加更多信息，
	 * 如果没有contextPath则需加上contextPath且加上国际化
	 */
	@Override
	public String buildUrl(String oriUrl) {
		String startStr = contextPath + "/" + getCurLocale().getLanguage();
		if (StringUtil.isNull(oriUrl)
				|| (StringUtils.isNotBlank(contextPath) && oriUrl
						.startsWith("/" + contextPath))
				|| oriUrl.startsWith(startStr)) {// contextPath不为空且地址以contextPath开始的路径不用操作，contextPath为空又是以/zh等开始
			return oriUrl;
		} else {
			String lanString = "/" + getCurLocale().getLanguage();
			if (oriUrl.startsWith("nolan:")) {
				lanString = "";
				oriUrl = oriUrl.replace("nolan:", "");
			}
			if (oriUrl.startsWith("/")) {
				return contextPath + lanString + oriUrl;
			} else {
				return contextPath + lanString + "/" + oriUrl;
			}

		}
	}

}
